package com.ycxy.school.express.service.impl;

import com.ycxy.school.express.ex.ServiceException;
import com.ycxy.school.express.mapper.OrderMapper;
import com.ycxy.school.express.mapper.PaymentMapper;
import com.ycxy.school.express.pojo.dto.PaymentAddNewDTO;
import com.ycxy.school.express.pojo.entity.Order;
import com.ycxy.school.express.pojo.entity.Payment;
import com.ycxy.school.express.service.IPaymentService;
import com.ycxy.school.express.util.UUIDUtils;
import com.ycxy.school.express.web.ServiceCode;
import com.ycxy.school.express.web.enums.PaymentStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @Author jayLuo
 * @Date 2023/1/10 17:28
 * @PackageName:com.ycxy.school.express.service.impl
 * @ClassName: PaymentServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Slf4j
@Service
public class PaymentServiceImpl implements IPaymentService {

    @Autowired
    private PaymentMapper paymentMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Transactional
    @Override
    public void createPayment(PaymentAddNewDTO paymentAddNewDTO) {
        log.debug("开始处理【生成订单支付数据】的业务，参数：{}", paymentAddNewDTO);
        //创建订单支付类
        Payment payment = new Payment();
        LocalDateTime now = LocalDateTime.now();
        String onlinePaymentNum = UUIDUtils.getUUID();
        //同名属性赋值
        BeanUtils.copyProperties(paymentAddNewDTO,payment);
        payment.setStatus(PaymentStatusEnum.TRADE_SUCCESS.getStatus());
        payment.setOnlinePaymentNum(onlinePaymentNum);
        payment.setModifiedData(now);

        //调用PaymentMapper的updateBySn方法
        int rows = paymentMapper.updateBySn(payment);
        // 判断修改数据的结果是否符合预期
        if (rows != 1) {
            String message = "生成支付数据失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }

        //修改订单中的支付时间字段数据
        //创建订单类
        Order order = new Order();
        order.setSn(paymentAddNewDTO.getOrderSn());
        order.setPayTime(now);
        order.setModifiedData(now);
        //调用OrderMapper的updateBySn方法
        int rows2 = orderMapper.updateBySn(order);
        // 判断修改数据的结果是否符合预期
        if (rows2 != 1) {
            String message = "修改创建时间字段数据失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }

    }
}
